package com.lanou3g.hw0516.hw0514.view;

import com.lanou3g.hw0516.hw0514.commons.Constant;
import com.lanou3g.hw0516.hw0514.controller.Controller;
import com.lanou3g.hw0516.hw0514.pojo.User;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@WebServlet(name = "loginServlet", urlPatterns = "/login")
public class loginServlet extends HttpServlet {
    private Controller controller = new Controller();

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //  获取数据
        String username = request.getParameter("username");
        String password = request.getParameter("password");

        User user = controller.login(username, password);
        String msg = "";

        // TODO 校验
        if (user != null) {
            msg = "登录成功";
            // 把user 存入session之前,把对象中的密码置空
            user.setPwd("");
            HttpSession session = request.getSession();
            session.setAttribute(Constant.Session.USER, user);


        } else {
            msg = " 登录失败";
        }
        request.setAttribute("msg", msg);
        request.getRequestDispatcher("/user/msg.jsp").forward(request, response);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request, response);
    }
}
